package 笔试;

import lombok.Data;

import java.util.*;

// 必须定义 `TreeTest` 入口类和 `public static void main(String[] args)` 入口方法
public class Tree2Test {
    @Data
    static class Node {
        int id;
        int parentId;
        String name;
        List<Node> child;

        public Node(int id, int parentId, String name) {
            this.id = id;
            this.parentId = parentId;
            this.name = name;
            child = new ArrayList<>();
        }
    }

    public static void main(String[] args) {
        List<Node> nodeList = Arrays.asList(
                new Node(1, 0, "AA"),
                new Node(2, 1, "BB"),
                new Node(3, 1, "CC"),
                new Node(4, 3, "DD"),
                new Node(5, 3, "EE"),
                new Node(6, 2, "FF"),
                new Node(7, 2, "GG"),
                new Node(8, 4, "HH"),
                new Node(9, 5, "II"),
                new Node(10, 0, "JJ"),
                new Node(11, 10, "KK"),
                new Node(12, 10, "LL"),
                new Node(13, 12, "MM"),
                new Node(14, 13, "NN"),
                new Node(15, 14, "OO")
        );
        print(nodeList);
    }

    public static void print(List<Node> nodeList) {
        print(nodeList, 0, 0);
    }

    public static void print(List<Node> nodeList, int parent, int level) {
        for (Node node : nodeList) {
            if (node.parentId == parent) {
                System.out.println();
                String tree = getTree(parent == 0 ? 0 : level + 1);
                System.out.print(tree + node.name);
                print(nodeList, node.id, level + 1);
            }
        }
    }

    //输出TAB，树形结构缩进
    private static String getTree(int time) {
        StringBuffer sb = new StringBuffer();
        if (time == 0) {
            return "";
        }
        for (int i = 1; i < time; i++) {
            sb.append("\t");
        }
        return sb.toString();
    }
}